package il.technion.cs236369.proxy;

import il.technion.cs236369.dal.CacheMangerFactoryImpl;
import il.technion.cs236369.exceptions.DatabaseException;
import il.technion.cs236369.exceptions.NotFoundException;
import il.technion.cs236369.exceptions.NotValidException;
import il.technion.cs236369.interfaces.ICacheManager;
import il.technion.cs236369.interfaces.IHttpCommunicator;

import java.io.IOException;
import java.net.Socket;
import java.util.Properties;

import javax.net.SocketFactory;

import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.HttpRequestHandler;

/**
 * HttpProxyHandler Class Implements HttpRequestHandler to be used by
 * HttpService.
 * 
 * @author Gil Fruchter 037023231 sgilf@t2
 * 
 */
public class HttpProxyHandler implements HttpRequestHandler, IHttpCommunicator {
	private static final int			HTTP_PORT	= 80;
	private final HttpProcessor			httpproc;
	private final HttpRequestExecutor	httpexecutor;
	private final SocketFactory			sockFactory;
	private final ICacheManager			cacheManager;
	private Socket						outsocket;
	private DefaultHttpClientConnection	outconn;

	/**
	 * Creates a new HttpProxyHandler to handle with outgoing http requests.
	 * 
	 * @param httpproc http processor for outgoing http requests.
	 * @param httpexecutor http executor for outgoing http requests.
	 * @param sockFactory socker factory to create outgoing connections with.
	 * @param props properties file for the cache manager.
	 */
	public HttpProxyHandler(HttpProcessor httpproc, HttpRequestExecutor httpexecutor, SocketFactory sockFactory, Properties props) {
		super();
		this.httpproc = httpproc;
		this.httpexecutor = httpexecutor;
		this.sockFactory = sockFactory;
		this.cacheManager = new CacheMangerFactoryImpl().create(this, props);
	}

	/**
	 * Closes the current outgoing socket and connection.
	 */
	public void closeConnections() {
//		try {
//			if (outsocket != null) {
//				outsocket.close();
//			}
//		} catch (IOException e) {
//			System.err.println("Can't close out socket");
//		}
		try {
			if (outconn != null) {
				outconn.close();
			}
		} catch (IOException e) {
			System.err.println("Can't close out connection");
		}
	}

	@Override
	public void handle(HttpRequest request, HttpResponse response, HttpContext context) {

		String url = request.getRequestLine().getUri();
		if (loadCache(request, response, context, url)) {
			return;
		}

		HttpHost httpHost = new HttpHost(request.getFirstHeader("Host").getValue(), HTTP_PORT);

		outsocket = null;
		outconn = null;
		try {
			outsocket = this.sockFactory.createSocket(httpHost.getHostName(), httpHost.getPort());
			outconn = new DefaultHttpClientConnection();
			outconn.bind(outsocket, request.getParams());
			context.setAttribute(ExecutionContext.HTTP_CONNECTION, outconn);
			context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);
			System.out.println(">> Request URI: " + url);

			// Remove hop-by-hop headers
			request.removeHeaders(HTTP.CONTENT_LEN);
			request.removeHeaders(HTTP.TRANSFER_ENCODING);
			request.removeHeaders(HTTP.CONN_DIRECTIVE);
			request.removeHeaders("Keep-Alive");
			request.removeHeaders("Proxy-Authenticate");
			request.removeHeaders("TE");
			request.removeHeaders("Trailers");
			request.removeHeaders("Upgrade");
			request.removeHeaders("Accept-Encoding");

			HttpResponse targetResponse = null;
			this.httpexecutor.preProcess(request, this.httpproc, context);
			targetResponse = this.httpexecutor.execute(request, outconn, context);
			handleResponse(response, context, url, targetResponse);
		} catch (Exception e) {
			response.setStatusLine(new BasicStatusLine(HttpVersion.HTTP_1_1, 500, "Internal Server Error"));
		}
	}

	private boolean loadCache(HttpRequest request, HttpResponse response, HttpContext context, String url) {
		try {
			for (Header header : request.getHeaders("Cache-Control")) {
				if (header.getValue().equals("no-cache")) {
					return false;
				}
			}
			HttpResponse cachedResponse = null;
			try {
				cachedResponse = cacheManager.load(request);
			} catch (NotValidException e) {
				System.err.println("!! could not validate response");
				handleResponse(response, context, url, e.getResponse());
				return true;
			}
			if (cachedResponse == null) {
				return false;
			}
			handleResponse(response, context, url, cachedResponse);
			System.out.println("< Loaded response from cache for URL: " + url);
			return true; 
		} catch (NotFoundException e) {
			System.out.println("!! cached response not found");
		} catch (DatabaseException e) {
			System.err.println("!! database error when trying to load cache");
		} catch (HttpException e) {
			System.err.println("!! error in handling response");
		} catch (IOException e) {
			System.err.println("!! error in handling response");
		}
		return false;
	}

	private void handleResponse(HttpResponse response, HttpContext context, String url, HttpResponse targetResponse) throws HttpException,
			IOException {
		this.httpexecutor.postProcess(response, this.httpproc, context);

		// Remove hop-by-hop headers
		targetResponse.removeHeaders(HTTP.CONTENT_LEN);
		targetResponse.removeHeaders(HTTP.TRANSFER_ENCODING);
		targetResponse.removeHeaders(HTTP.CONN_DIRECTIVE);
		targetResponse.removeHeaders("Keep-Alive");
		targetResponse.removeHeaders("TE");
		targetResponse.removeHeaders("Trailers");
		targetResponse.removeHeaders("Upgrade");
		targetResponse.removeHeaders("Accept-Encoding");

		response.setStatusLine(targetResponse.getStatusLine());
		response.setHeaders(targetResponse.getAllHeaders());
		response.setEntity(targetResponse.getEntity());
		response.setStatusCode(targetResponse.getStatusLine().getStatusCode());
		storeResponse(response, url);

		System.out.println("<< Response: " + response.getStatusLine());
	}

	private void storeResponse(HttpResponse response, String url) throws IOException {
		try {
			boolean result = cacheManager.store(url, response);
			System.out.println("!! was stored: " + result + " for url: " + url);
		} catch (DatabaseException e) {
			System.out.println("!! could not store response");
		}
	}

	@Override
	public HttpResponse get(HttpRequest request) {
		HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 0, null);
		handle(request, response, new BasicHttpContext());
		return response;
	}
}
